package training.list.refimpl;

import training.list.ListNode;
import training.list.ReverseListBetween;

public class ReverseListBetweenSolution implements ReverseListBetween {

    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        ListNode newHead = new ListNode(-1);
        newHead.next = head;
        ListNode p1 = newHead;
        ListNode p2 = head;
        int i = 1;
        while (i < m) {
            p1 = p1.next;
            p2 = p2.next;
            i++;
        }
        ListNode mhead = p1;
        ListNode mend = p2;
        p1 = null;

        while (i<=n) {
            ListNode temp = p2.next;
            p2.next = p1;
            p1 = p2;
            p2 = temp;
            i++;
        }
        mhead.next = p1;
        mend.next = p2;

        return newHead.next;
    }

}
